package com.contract.spirit.ui.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.contract.commonlib.webview.MyWebChromeClient;
import com.contract.commonlib.webview.MyWebViewClient;
import com.contract.spirit.BuildConfig;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import java.lang.reflect.Field;

@SuppressLint("JavascriptInterface")
public class WebViewUtil {

    @SuppressLint("SetJavaScriptEnabled")
    public static void initWebview(Context context, WebView mWebView, final ProgressBar pb, TextView titleView) {
        try {
            WebSettings settings = mWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setAllowFileAccess(true);
            settings.setDomStorageEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);
            settings.setAppCacheEnabled(true);
            settings.setSavePassword(false);
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        mWebView.setDownloadListener(new MyWebViewDownLoadListener(context));
        MyWebChromeClient myWebChromeClient = new MyWebChromeClient();
        myWebChromeClient.setProgressBar(pb);
        myWebChromeClient.setTitleView(titleView);
        mWebView.setWebChromeClient(myWebChromeClient);
        mWebView.setWebViewClient(new MyWebViewClient());
        CookieManager.getInstance().acceptThirdPartyCookies(mWebView);
    }

    public static void initWebview(Context context, WebView mWebView, final ProgressBar pb) {
        initWebview(context, mWebView, pb, null);
    }

    public static Android addJSInterface(Activity activity, WebView mWebView) {
        Android scripInterface = new Android(activity);
        mWebView.addJavascriptInterface(scripInterface, "Android");
        mWebView.addJavascriptInterface(new ExternalJsInterface(activity, mWebView), "android");
        return scripInterface;
    }

    static class Android {
        Activity activity;
        Handler handler = new Handler(Looper.getMainLooper());

        public Android(Activity c) {
            this.activity = c;
        }


        @JavascriptInterface
        public void finish() {
            activity.finish();
        }


        @JavascriptInterface
        public void toast(String msg) {
            ToastUtils.showLong(msg);
        }

        @JavascriptInterface
        public void reloadOnResume() {
            try {
                Field webviewrefresh = activity.getClass().getField("webViewRefresh");
                webviewrefresh.set(activity, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public int getClientVer() {
            return BuildConfig.VERSION_CODE;
        }

        @JavascriptInterface
        public String android_int() {
            return String.valueOf(Build.VERSION.SDK_INT);
        }

    }

    static class ExternalJsInterface {

        Activity activity;

        WebView webView;

        public ExternalJsInterface(Activity c, WebView webView) {
            this.activity = c;
            this.webView = webView;
        }

        /**
         * 此方法实现，外部浏览器打开指定url功能
         */
        @JavascriptInterface
        public void Browser(String downurl) {
            Intent intent = new Intent();
            Uri content_url = Uri.parse(downurl);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(content_url);
            activity.startActivity(intent);
        }
    }

    public static void clearWebview(WebView mWebView) {
        if (mWebView != null) {
            try {
                ((ViewGroup) mWebView.getParent()).removeAllViews();
                mWebView.stopLoading();
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                mWebView.getSettings().setJavaScriptEnabled(false);
                mWebView.clearCache(true);
                mWebView.clearView();
                mWebView.clearHistory();
                mWebView.removeAllViews();
                mWebView.destroy();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    }
}
